WebWorker

class WebWorker

A Web Worker that runs a self-contained JavaScript job off the main thread on Kotlin/JS.

The worker is created at runtime from a Blob URL rather than a separate script file. The job runs in the Worker scope with no access to the Kotlin module. Pass everything it needs through the payload String and JSON-encode it for structure. jobJs is a JavaScript function expression (payload) => result, synchronous or asynchronous.

Each reply carries a correlation id. A reply to a cancelled call is dropped instead of being delivered to the next caller, so call is safe to cancel. Wrap call in withTimeout to apply a deadline.

suspend fun sumTo(n: String): String {
val w = WebWorker.of("(n) => { let s = 0; for (let i = 0; i < +n; i++) s += i; return '' + s }")
return try { w.call(n) } finally { w.close() } // call() runs off the main thread
}

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
suspend fun call(payload: String): String

Runs the job with payload and suspends until the worker replies.

Link copied to clipboard
fun close()

Terminates the underlying Worker. An in-flight call fails with WebWorkerException. Idempotent.